package org.hardcode.rpc.common.scanner.server;

import javassist.bytecode.stackmap.TypeData;
import org.hardcode.rpc.annotation.RpcService;
import org.hardcode.rpc.common.helper.RpcServiceHelper;
import org.hardcode.rpc.common.scanner.ClassScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class RpcServerScanner extends ClassScanner {

    private static final Logger logger = LoggerFactory.getLogger(RpcServerScanner.class);

    //扫描指定表下的类，并筛选@RpcService注解标注的类
    public static Map<String, Object> doScannerWithRpcServiceAnnotationFilterAndRegistryService(String scanPackage) throws IOException {
        Map<String, Object> handlerMap = new HashMap<>();


        List<String> classNameList = getClassNameList(scanPackage, true);

        if (classNameList == null || classNameList.isEmpty()) {
            return handlerMap;
        }


        //不方便调试

        classNameList.stream().forEach(className -> {
            try {
                Class<?> aClass = Class.forName(className);
                RpcService rpcService = aClass.getAnnotation(RpcService.class);
                if (rpcService != null) {
                    String serverName = getServerName(rpcService);
                    //修改key
                  //  String key = serverName.concat(rpcService.group()).concat(rpcService.version());
                    String key = RpcServiceHelper.buildServiceKey(serverName,rpcService.version(),rpcService.group());

                    handlerMap.put(key, aClass.newInstance());
                }


            } catch (ClassNotFoundException e) {
                logger.error("e:{}", e);
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });


        return handlerMap;
    }

    public static String getServerName(RpcService rpcService) {
        return rpcService.interfaceClassName();
    }
}
